<template>
  <div>
    <a-card class="card-header">
      <a-form-model :model="queryParam">
        <a-row :gutter="24">
          <a-col :span="5">
            <a-form-model-item
              label="商品名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-model.trim="queryParam.goodsName"
                placeholder="请输入商品名称"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="5">
            <a-form-model-item
              label="商品编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-model.trim="queryParam.goodsCode"
                placeholder="请输入商品编号"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="5" v-hasPromise="'commodityDel'">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="状态"
            >
              <a-select
                style="width: 100%"
                v-model.trim="queryParam.deleteFlag"
              >
                <a-select-option
                  v-for="item in deleteOption"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="2">
            <a-button
              type="primary"
              style="margin-top:3px"
              @click="handleSearch('goodsType')"
              >查询</a-button
            >
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>

    <a-card class="card-content">
      <a-row :gutter="24">
        <a-col :span="22">
          <a-button type="primary" @click="handleTypeAdd"
            >新建商品类型</a-button
          >
          <a-button type="primary" @click="handleAdd">新建商品</a-button>
          <a-button type="primary" @click="handleBatchCode">批量生成</a-button>
          <a-button type="primary" @click="handleDown">导出</a-button>
          <!-- <a-button
            type="primary"
            @click="
              handelExport('商品管理列表', 'CommodityList', CommodityColumns)
            "
            >导出</a-button
          >
          <a-button
            type="primary"
            @click="handelExportTemplate('商品管理列表模板', CommodityColumns)"
            >导出模板</a-button
          > -->
          <!-- <a-button type="primary" @click="handelImport">导入</a-button> -->
          <input
            type="file"
            id="fileTemp"
            ref="fileTemp"
            v-show="false"
            accept=".xls, .xlsx, .excel"
            @input="getImportFile"
          />
        </a-col>
        <a-col :span="2">
          <a-button type="primary" @click="handleAllList('Commodity')"
            >全部商品</a-button
          >
        </a-col>
      </a-row>
      <br />
      <a-row :gutter="16">
        <a-col :span="5">
          <div class="treeBox">
            <div class="tree-title">商品类型</div>

            <a-tree
              :checkable="false"
              :show-line="true"
              :tree-data="treeData"
              @select="onSelect"
              :selectedKeys="selectedKeys"
              :replaceFields="replaceFields"
            >
              <template slot="custom" slot-scope="record">
                <div class="flex flex-a-c flex-j-s-b">
                  <div>{{ record.goodsTypeName }}</div>
                  <div>
                    <a-icon
                      type="edit"
                      class="icon-edit"
                      @click="handleTypeEdit(record)"
                    />
                    <a-popconfirm
                      v-hasPromise="'commodityDel'"
                      title="确定删除吗?"
                      @confirm="handleTypeDelete(record)"
                    >
                      <a-icon class="icon-delete" type="delete" />
                    </a-popconfirm>
                  </div>
                </div>
              </template>
            </a-tree>
          </div>
        </a-col>
        <a-col :span="19">
          <a-table
            :columns="columns"
            :data-source="tableData"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            bordered
            :rowKey="
              (record, index) => {
                return record.id;
              }
            "
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
          >
            <template slot="action" slot-scope="text, record">
              <div v-if="record.deleteFlag === 'N'">
                <a @click="handleEdit(record)">编辑</a>
                <a-divider type="vertical" v-hasPromise="'commodityDel'" />
                <a-popconfirm
                  v-hasPromise="'commodityDel'"
                  okText="确定"
                  cancelText="取消"
                  title="确定删除吗?"
                  @confirm="() => handleDelete(record)"
                >
                  <a>删除</a>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a-icon
                  type="qrcode"
                  @click.stop="handleCode(record)"
                  style="fontSize: 16px;color: #40a9ff;"
                />
              </div>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-card>
    <!-- 商品弹框 -->
    <CommodityModal
      ref="modalForm"
      :treeData="treeData"
      @ok="modalFormOk"
      @getTree="getTree"
    ></CommodityModal>
    <!-- 商品二维码弹框 -->
    <CommodityTypeModal
      ref="modalTypeForm"
      :treeData="treeData"
      @ok="modalTypeFormOk"
    ></CommodityTypeModal>

    <!-- 二维码 -->
    <qrCode
      ref="qrCode"
      :label="qrModel.label"
      :text="qrModel.text"
      :qrSize="320"
    ></qrCode>
    <codeImage ref="codeImage" @setRowKeys="setRowKeys"></codeImage>
  </div>
</template>

<script>
import { columns, CommodityColumns } from "./components/tableConfig";
import { tableMinxins } from "@/unit/mixins/tableMinxins.js";
import { setTreeData } from "@/unit/tool";
import CommodityModal from "@/components/CommodityModal.vue";
import CommodityTypeModal from "./components/CommodityTypeModal.vue";
import qrCode from "@/components/qrCode";
import api from "@/api/apiServer";
import codeImage from "@/components/codeImage";
import { CodeNo } from "@/unit/QRCodeConfig";
export default {
  components: { CommodityModal, CommodityTypeModal, qrCode, codeImage },
  mixins: [tableMinxins],
  data() {
    return {
      columns,
      CommodityColumns,
      treeData: [],
      replaceFields: {
        children: "goodsTypeList",
        title: "goodsTypeName",
        key: "id",
        value: "id",
      },
      queryParam: {
        deleteFlag: "N",
      },
      deleteOption: [
        { value: "Y", label: "已删除" },
        { value: "N", label: "当前存在" },
      ],
      qrModel: {
        label: "", // 二维码底部内容
        text: "", // 二维码内容
      },
      goodsOption: [], // 商品选择数据源
      selectedKeys: [], // 侧边栏选中
      dataSource: [], //表格选中的数据
    };
  },
  mounted() {
    this.getTree();
    this.getList();
  },
  methods: {
    handleBatchCode() {
      let newArr = this.dataSource.filter((item) => {
        if (this.selectedRowKeys.includes(item.id)) {
          return item;
        }
      });
      let tableData = newArr.map((item) => {
        let { id, goodsCode, goodsName, specifications } = item;
        return {
          title: `${item.goodsCode} ${item.goodsName}`,
          label: `${item.goodsCode} ${item.goodsName}`,
          text: JSON.stringify({
            id,
            goodsCode,
            goodsName,
            specifications,
            QRCode: CodeNo.Commodity,
          }),
        };
      });

      this.$refs.codeImage.title = "商品二维码";
      this.$refs.codeImage.showModal(tableData, "商品");
    },
    // 清空选中的数据
    setRowKeys() {
      this.selectedRowKeys = [];
    },
    arrDistinctByProp(arr, prop) {
      //只返回第一次出现的，重复出现的过滤掉
      return arr.filter(function(item, index, self) {
        return self.findIndex((el) => el[prop] == item[prop]) === index;
      });
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // 导入接口
    async setImport(list) {
      const res = await api.CommodityAllAdd({ list });
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.$message.success(res.message);
      this.getList();
    },
    handleReset() {
      this.selectedKeys = [];
      this.getList();
    },
    modalFormOk() {
      this.queryParam = {};
      this.queryParam.deleteFlag = "N";
      // 新增/修改 成功时，重载列表
      this.getList();
      //清空列表选中
      this.onClearSelected();
    },
    // 商品查询
    handleGoodSearch(goodsName) {
      this.getGoodList(goodsName);
    },
    // 获取商品列表
    async getGoodList(goodsName) {
      let params = { pageNumber: 1, pageSize: 10 };
      if (goodsName) {
        params.goodsName = goodsName;
        const res = await api.CommodityList(params);
        this.goodsOption = res.data.data;
      }
    },
    // 获取列表数据
    async getList(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.pagination.current = 1;
      }
      var params = this.getQueryParams();
      const res = await api.CommodityList(params);
      this.pagination.total = res.data.total;
      this.tableData = res.data.data;
      let newArr = [...res.data.data, ...this.dataSource];
      this.dataSource = this.arrDistinctByProp(newArr, "id");
    },

    // 获取树数据
    async getTree() {
      const res = await api.CommodityTypeFindAll();
      this.treeData = setTreeData(res.data, "custom", "goodsTypeList");
    },
    // 商品类型新增
    handleTypeAdd() {
      this.$refs.modalTypeForm.title = "新增";
      this.$refs.modalTypeForm.modalAdd();
    },
    // 商品类型编辑
    handleTypeEdit(record) {
      this.$refs.modalTypeForm.title = "编辑";
      this.$refs.modalTypeForm.modalEdit(record);
    },
    // 删除
    async handleTypeDelete(record) {
      let params = {
        id: record.id,
      };
      const res = await api.CommodityTypeDelete(params);
      this.$message.success(res.message);
      this.getTree();
    },
    // 生成二维码
    handleCode(record) {
      let { goodsCode, goodsName, specifications, id } = record;
      let newObj = {
        id,
        goodsCode,
        goodsName,
        specifications,
        QRCode: CodeNo.Commodity,
      };
      let text = JSON.stringify(newObj);
      this.$refs.qrCode.title = "商品二维码";
      this.qrModel.label = `${goodsCode} ${goodsName}`;
      this.qrModel.text = text;
      this.$refs.qrCode.list = this.qrModel.label.split(",");
      this.$refs.qrCode.showModal();
    },
    // 新增/修改 成功时，重载列表
    modalTypeFormOk() {
      this.getTree();
    },

    async handleDelete(record) {
      let params = {
        id: record.id,
      };
      const res = await api.CommodityDelete(params);
      this.$message.success(res.message);
      this.getList();
    },
    onSelect(selectedKeys, info) {
      this.pagination.current = 1;
      this.pagination.pageNumber = 1;
      this.selectedKeys = selectedKeys;
      this.queryParam.goodsType = selectedKeys[0];
      this.getList();
    },
    async handleDown() {
      const content = await api.Dome(
        { pageNumber: 1, pageSize: 10, deleteFlag: "N" },
        { responseType: "blob" }
      );
      const blob = new Blob([content], {
        type: "application/vnd.ms-excel;charset=utf-8",
      });
      const fileName = "商品信息.xlsx";
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
    },
  },
};
</script>

<style lang="less" scoped>
.card-header {
  margin: 20px 0;
}
.card-content {
  button {
    margin-right: 20px;
  }
}
::v-deep .ant-tree-node-content-wrapper {
  width: 90%;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
</style>
